- Notifications
You must be signed in to change notification settings - Fork 5.8k
/
Copy path2096. Step-By-Step Directions From a Binary Tree Node to Another.go
77 lines (66 loc) · 1.37 KB
/
2096. Step-By-Step Directions From a Binary Tree Node to Another.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package leetcode
import (
"github.com/halfrost/LeetCode-Go/structures"
)
// TreeNode define
typeTreeNode= structures.TreeNode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
funcgetDirections(root*TreeNode, startValueint, destValueint) string {
sPath, dPath:=make([]byte, 0), make([]byte, 0)
findPath(root, startValue, &sPath)
findPath(root, destValue, &dPath)
size, i:=min(len(sPath), len(dPath)), 0
fori<size {
ifsPath[len(sPath)-1-i] ==dPath[len(dPath)-1-i] {
i++
} else {
break
}
}
sPath=sPath[:len(sPath)-i]
replace(sPath)
dPath=dPath[:len(dPath)-i]
reverse(dPath)
sPath=append(sPath, dPath...)
returnstring(sPath)
}
funcfindPath(root*TreeNode, valueint, path*[]byte) bool {
ifroot.Val==value {
returntrue
}
ifroot.Left!=nil&&findPath(root.Left, value, path) {
*path=append(*path, 'L')
returntrue
}
ifroot.Right!=nil&&findPath(root.Right, value, path) {
*path=append(*path, 'R')
returntrue
}
returnfalse
}
funcreverse(path []byte) {
left, right:=0, len(path)-1
forleft<right {
path[left], path[right] =path[right], path[left]
left++
right--
}
}
funcreplace(path []byte) {
fori:=0; i<len(path); i++ {
path[i] ='U'
}
}
funcmin(i, jint) int {
ifi<j {
returni
}
returnj
}